package com.mine.dubbo.zookeeper;

import lombok.extern.log4j.Log4j2;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

@Log4j2
public class ZooKeeperClient {
    private ZooKeeper client;

    public ZooKeeperClient(String host, int port) throws IOException, InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(1);
        client = new ZooKeeper(String.format("%s:%d", host, port), 4000000, event -> {
            System.out.println(event.getState());
            countDownLatch.countDown();
        });
        countDownLatch.await();
        log.info("成功创建zookeeper");
    }

    public void createEphemeralNode(String path) {
        try {
            client.create(path, "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        } catch (KeeperException | InterruptedException e) {
            log.error(e);
        }
    }
}
